//
//  MainSocketDelegate.m
//  TcpTest_Server
//
//  Created by scarlettsun on 12-7-28.
//  Copyright (c) 2012年 tencent. All rights reserved.
//

#import "MainSocketDelegate.h"
#import "MiniSocket.h"

@implementation MainSocketDelegate
@synthesize listenSocket;

static NSMutableArray *connectedSocketsQueue;
static NSMutableArray *theHeartBeatQueue;
static NSMutableArray *thePacketQueue;

+(NSMutableArray *)connectedSocketsQueue
{
    if (connectedSocketsQueue == nil) {
        connectedSocketsQueue = [[NSMutableArray alloc] init];
    }
    return connectedSocketsQueue;
}
+(NSMutableArray *)theHeartBeatQueue
{
    if (theHeartBeatQueue == nil) {
        theHeartBeatQueue = [[NSMutableArray alloc] init];
    }
    return theHeartBeatQueue;
}
+(NSMutableArray *)thePacketQueue
{
    if (thePacketQueue == nil) {
        thePacketQueue = [[NSMutableArray alloc] init];
    }
    return thePacketQueue;
}

- (id)init     //WithQueue:(dispatch_queue_t)socketQueue 
{
    serverPort = [[NSUserDefaults standardUserDefaults] integerForKey:@"LISTEN_PORT"];
    serverPort = (serverPort == 0) ?  SERVER_PORT : serverPort;
    socketQueue =dispatch_queue_create("socketQueue", NULL);  
    self.listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];
    isRunning = false;
    return self;
}

//send short message
- (void)startStop{
	if(!isRunning)
	{
		NSError *error = nil;
		if(![self.listenSocket acceptOnPort:serverPort error:&error])
		{
            NSLog(@"MainSocketDelegate 监听失败");
			return;
		}
		NSLog(@"MainSocketDelegate 开始监听%lu",serverPort);
		isRunning = YES; 
	}
	else
	{	
        NSLog(@"MainSocketDelegate 删除重新监听");
		[self.listenSocket disconnect]; 
        [[MainSocketDelegate connectedSocketsQueue] removeAllObjects];
		isRunning = false;
	}
}
- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket;
{	
    [newSocket readDataToLength:LENGTH withTimeout:-1 tag:0];  /*has to be set here */
    MiniSocket *miniSocket = [[MiniSocket alloc] initWithSock:newSocket];
    @synchronized([MainSocketDelegate connectedSocketsQueue])
    {
     [[MainSocketDelegate connectedSocketsQueue] addObject:miniSocket];
    }
    NSLog(@"MainSocketDelegate  didAcceptNewSocket\r\n");
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
{
    NSLog(@"MainSocketDelegate  didConnectToHost\r\n");
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;
{
    NSLog(@"MainSocketDelegate  didWriteDataWithTag\r\n");
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
{
    NSLog(@"MainSocketDelegate did read sock%@",sock.description);
}

/*- (void)Socket:(GCDAsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"%s %d", __FUNCTION__, __LINE__);
}*/

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err;
{
    self.listenSocket = nil;
    isRunning = false;
}



@end
